package com.fastloan.mgt.three.baidu;

import com.alibaba.fastjson.JSONObject;
import com.fastloan.core.kuaixin.baidu.BaiDuModel;
import com.fastloan.mgt.application.base.enums.ApplicationStatusEnum;
import com.fastloan.mgt.application.base.model.Application;
import com.fastloan.mgt.application.base.service.ApplicationService;
import com.fastloan.mgt.customer.model.ZyCustomer;
import com.fastloan.mgt.customer.service.ZyCustomerService;
import com.fastloan.mgt.processcontrol.base.annotation.FunctionHandlerClass;
import com.fastloan.mgt.processcontrol.base.annotation.FunctionHandlerMethod;
import com.fastloan.mgt.processcontrol.base.model.ProcessSession;
import com.fastloan.mgt.processcontrol.base.service.ProcessDispatcher;
import com.fastloan.mgt.product.flow.enums.ProductFunctionGroup;
import com.fastloan.mgt.three.baidu.bean.BlackScore;
import com.fastloan.mgt.three.baidu.bean.MultiScore;
import com.fastloan.mgt.three.baidu.bean.Risk;
import com.fastloan.mgt.three.bean.ZyApplicationThreeModel;
import com.fastloan.mgt.three.service.ZyApplicationThreeModelService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author rankai
 *         createTime 2017-11-2017/11/17 11:31
 */
@Service
@FunctionHandlerClass(processName = "百度反欺诈", bmpIds = {ProductFunctionGroup.GROUP_ONE})
public class BaiduApp {

    private static final Logger log = LoggerFactory.getLogger(BaiduApp.class);

    private static final String MODEL_NAME = "百度模型";

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private ZyCustomerService customerService;

    @Autowired
    private ZyApplicationThreeModelService applicationThreeModelService;

    @FunctionHandlerMethod
    @Transactional
    public void baiduModel(String processId) {
        ProcessSession processSession = ProcessDispatcher.getProcessSession(processId);
        String applicationId = processSession.getAttribute("applicationId", String.class);
        Application application = applicationService.selectByPrimaryKey(applicationId);
        applicationService.modifyApplicationStatus(applicationId, ApplicationStatusEnum.BAIDU_MODEL);
        ZyCustomer zyCustomer = customerService.selectByPrimaryKey(application.getCustomerId());
        String cardNum = zyCustomer.getCardNum();
        String phoneNum = zyCustomer.getPhoneNum();
        String cname = zyCustomer.getCname();
        if (StringUtils.isNotBlank(cardNum) && StringUtils.isNotBlank(phoneNum) && StringUtils.isNotBlank(cname)) {
            String blackScoreStr = BaiDuModel.blackScore(cname, cardNum, phoneNum);
            BlackScore blackScore = JSONObject.parseObject(blackScoreStr, BlackScore.class);
            String multiScoreStr = BaiDuModel.multiScore(cname, cardNum, phoneNum);
            MultiScore multiScore = JSONObject.parseObject(multiScoreStr, MultiScore.class);
            String riskStr = BaiDuModel.risk(cname, cardNum, phoneNum);
            Risk risk = JSONObject.parseObject(riskStr, Risk.class);
            int count = 0;
            ZyApplicationThreeModel zyApplicationThreeModel = new ZyApplicationThreeModel();
            zyApplicationThreeModel.setAppId(applicationId);
            zyApplicationThreeModel.setThreeGroup(MODEL_NAME);
            if (risk.getRet() == 0) {
                Risk.DataBean.ResultBean result = risk.getData().getResult();
                String blackLevel = result.getBlackLevel();
                zyApplicationThreeModel.setBaiduBlacklevel(blackLevel);
                log.info("百度风险等级:{}", blackLevel);
                if ("A".equals(blackLevel) || "B".equals(blackLevel)) {
                    applicationService.modifyApplicationStatus(applicationId, ApplicationStatusEnum.BAIDU_MODEL_REJECT);
                    ProcessDispatcher.executeEnd(processId, false);
                    return;
                } else if ("C".equals(blackLevel) || "D".equals(blackLevel)) {
                    count += 1;
                }
            }
            if (blackScore.getRet() == 0) {
                BlackScore.DataBean.ResultBean result = blackScore.getData().getResult();
                zyApplicationThreeModel.setBaiduBlackscore(String.valueOf(result.getBlackScore()));
                if (result.getBlackScore() > 20) {
                    count += 1;
                }
            }
            if (multiScore.getRet() == 0) {
                MultiScore.DataBean.ResultBean result = multiScore.getData().getResult();
                List<String> valuesPhone = result.getPhone().getValues();
                List<String> valueIdentity = result.getIdentity().getValues();
                List<String> valuesName = result.getName().getValues();
                MultiScoreResBean valuesNameBean = multiScore(valuesName);
                MultiScoreResBean valuesPhoneBean = multiScore(valuesPhone);
                MultiScoreResBean valueIdentityBean = multiScore(valueIdentity);
                count += (valuesNameBean.count + valuesPhoneBean.count + valueIdentityBean.count);
                StringBuffer sb = new StringBuffer();
                sb.append(valuesNameBean.score).append(",")
                        .append(valuesPhoneBean.score).append(",")
                        .append(valueIdentityBean.score);
                zyApplicationThreeModel.setBaiduMultiscore(sb.toString());
            }
            applicationThreeModelService.insertSelective(zyApplicationThreeModel);
            if (count >= 2) {
                //拒绝
                applicationService.modifyApplicationStatus(applicationId, ApplicationStatusEnum.BAIDU_MODEL_REJECT);
                ProcessDispatcher.executeEnd(processId, false);
            } else {
                ProcessDispatcher.executeEnd(processId, true);
            }
        } else {
            log.warn("百度模型用户参数错误,身份证:{}>>手机号:{}>>姓名:{}", cardNum, phoneNum, cname);
            applicationService.modifyApplicationStatus(applicationId, ApplicationStatusEnum.BAIDU_MODEL_REJECT);
            ProcessDispatcher.executeEnd(processId, false);
        }
    }

    private MultiScoreResBean multiScore(List<String> valuesName) {
        if (valuesName.size() > 0) {
            String s = valuesName.get(0);
            log.debug("黑产分析分数>>分数:{}", s);
            int parseInt = Integer.parseInt(s);
            if (parseInt > 20) {
                new MultiScoreResBean(1, parseInt);
            }
        }
        return new MultiScoreResBean(0, 0);
    }

    class MultiScoreResBean {

        private int count;

        private int score;

        public MultiScoreResBean(int count, int score) {
            this.count = count;
            this.score = score;
        }
    }
}
